package com.qf.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qf.mapper.DtsAdminMapper;
import com.qf.pojo.DtsAdmin;
import com.qf.service.AdminService;
import com.qf.util.bcrypt.BCryptPasswordEncoder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;

@Service
public class AdminServiceImpl implements AdminService{

    @Autowired
    private DtsAdminMapper adminMapper;

    @Override
    public List<DtsAdmin> findAdminByUserName(String userName) {
        QueryWrapper<DtsAdmin> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", userName);

        List<DtsAdmin> list = adminMapper.selectList(queryWrapper);
        return list;
    }

    @Override
    public IPage<DtsAdmin> findByPage(Integer page, Integer limit, String username, String sort, String order) {
        Page<DtsAdmin> pageParam = new Page<>(page,limit);
        QueryWrapper<DtsAdmin> queryWrapper = new QueryWrapper<>();
        if (!StringUtils.isEmpty(username)) {
            queryWrapper.like("username", username);
        }
        if ("asc".equalsIgnoreCase(order)){
            queryWrapper.orderByAsc(sort);
        }else {
            queryWrapper.orderByDesc(sort);
        }

        Page<DtsAdmin> pageResult = adminMapper.selectPage(pageParam, queryWrapper);

        return pageResult;
    }

    @Override
    public DtsAdmin insert(DtsAdmin admin) {
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        admin.setPassword(encoder.encode(admin.getPassword()));
        admin.setAddTime(new Date());
        admin.setUpdateTime(new Date());
        admin.setDeleted(false);

        adminMapper.insert(admin);
        return admin;
    }

    @Override
    public int updateById(DtsAdmin admin) {
        admin.setUpdateTime(new Date());
        return adminMapper.updateById(admin);
    }

    @Override
    public void deleteById(Integer id) {
        adminMapper.deleteById(id);
    }

    @Override
    public List<DtsAdmin> findAll() {
        QueryWrapper<DtsAdmin> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("deleted", 0);
        List<DtsAdmin> adminList = adminMapper.selectList(queryWrapper);
        return adminList;
    }
}
